package com.google.code.sms.android.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import com.google.code.sms.android.R;

import java.util.Arrays;

import com.google.code.sms.android.service.DownloadService;
import com.google.code.sms.android.service.DownloadServiceImpl;
import com.google.code.sms.android.util.Constants;
import com.google.code.sms.android.util.FileUtil;
import com.google.code.sms.android.util.MergeAdapter;
import com.google.code.sms.android.util.PopupMenuHelper;
import com.google.code.sms.android.util.ServerSettingsManager;
import com.google.code.sms.android.util.Util;

public class MainActivity extends SMSTabActivity {

    private static final int MENU_GROUP_SERVER = 10;

    private TextView serverTextView;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getIntent().hasExtra(Constants.INTENT_EXTRA_NAME_EXIT)) {
            exit();
        }
        setContentView(R.layout.main);

        loadSettings();

        View buttons = LayoutInflater.from(this).inflate(R.layout.main_buttons, null);

        final View serverButton = buttons.findViewById(R.id.main_select_server);
        serverTextView = (TextView) serverButton.findViewById(R.id.main_select_server_2);

        final TextView offlineButton = (TextView) buttons.findViewById(R.id.main_offline);
        offlineButton.setText(Util.isOffline(this) ? R.string.main_use_connected : R.string.main_use_offline);

        final View albumsTitle = buttons.findViewById(R.id.main_albums);
        final View albumsNewestButton = buttons.findViewById(R.id.main_albums_newest);
        final View albumsRecentButton = buttons.findViewById(R.id.main_albums_recent);
        final View albumsFrequentButton = buttons.findViewById(R.id.main_albums_frequent);

        final View dummyView = findViewById(R.id.main_dummy);

        ListView list = (ListView) findViewById(R.id.main_list);

        MergeAdapter adapter = new MergeAdapter();

        adapter.addView(offlineButton, true);
        if (!Util.isOffline(this)) {
            adapter.addView(serverButton, true);
            adapter.addView(albumsTitle, false);
            adapter.addViews(Arrays.asList(albumsNewestButton, albumsRecentButton, albumsFrequentButton), true);
        }
        list.setAdapter(adapter);
        registerForContextMenu(dummyView);

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (view == offlineButton) {
                    toggleOffline();
                } else if (view == serverButton) {
                    dummyView.showContextMenu();
                } else if (view == albumsNewestButton) {
                    showAlbumList("newest");
                } else if (view == albumsRecentButton) {
                    showAlbumList("recent");
                } else if (view == albumsFrequentButton) {
                    showAlbumList("frequent");
                }
            }
        });

        setTitle(R.string.common_appname);

        // Button 1: search
        ImageButton actionSearchButton = (ImageButton)findViewById(R.id.action_button_1);
        actionSearchButton.setImageResource(R.drawable.action_search);
        actionSearchButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                onSearchRequested();
            }
        });

        // Button 2: overflow
        final View overflowButton = findViewById(R.id.action_button_2);
        overflowButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                new PopupMenuHelper().showMenu(MainActivity.this, overflowButton, R.menu.main);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        serverTextView.setText(Util.getActiveServer(this).getName());
    }

    private void loadSettings() {
        PreferenceManager.setDefaultValues(this, R.xml.settings, false);
        SharedPreferences prefs = Util.getPreferences(this);
        if (!prefs.contains(Constants.PREFERENCES_KEY_CACHE_LOCATION)) {
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString(Constants.PREFERENCES_KEY_CACHE_LOCATION, FileUtil.getDefaultMediaDirectory().getPath());
            editor.commit();
        }

        if (!prefs.contains(Constants.PREFERENCES_KEY_OFFLINE)) {
            SharedPreferences.Editor editor = prefs.edit();
            editor.putBoolean(Constants.PREFERENCES_KEY_OFFLINE, false);
            editor.commit();
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, view, menuInfo);

        ServerSettingsManager serverSettingsManager = new ServerSettingsManager(this);
        ServerSettingsManager.ServerSettings activeServer = serverSettingsManager.getActiveServer();

        for (ServerSettingsManager.ServerSettings server : serverSettingsManager.getAllServers()) {
            MenuItem menuItem = menu.add(MENU_GROUP_SERVER, server.getId(), server.getId(), server.getName());
            if (activeServer.getId() == server.getId()) {
                menuItem.setChecked(true);
            }
        }

        menu.setGroupCheckable(MENU_GROUP_SERVER, true, true);
        menu.setHeaderTitle(R.string.main_select_server);
    }

    @Override
    public boolean onContextItemSelected(MenuItem menuItem) {
        ServerSettingsManager serverSettingsManager = new ServerSettingsManager(this);
        if (menuItem.getItemId() == serverSettingsManager.getActiveServer().getId()) {
            return true;
        }

        serverSettingsManager.setActiveServerId(menuItem.getItemId());
        DownloadService service = getDownloadService();
        if (service != null) {
            service.clearIncomplete();
        }

        // Restart activity
        restart();
        return true;
    }

    private void toggleOffline() {
        Util.setOffline(this, !Util.isOffline(this));
        restart();
    }

    private void restart() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        Util.startActivityWithoutTransition(this, intent);
    }

    private void exit() {
        stopService(new Intent(this, DownloadServiceImpl.class));
        finish();
    }

    private void showAlbumList(String type) {
        Intent intent = new Intent(this, SelectAlbumActivity.class);
        intent.putExtra(Constants.INTENT_EXTRA_NAME_ALBUM_LIST_TYPE, type);
        intent.putExtra(Constants.INTENT_EXTRA_NAME_ALBUM_LIST_SIZE, 20);
        intent.putExtra(Constants.INTENT_EXTRA_NAME_ALBUM_LIST_OFFSET, 0);
        Util.startActivityWithoutTransition(this, intent);
    }
}